package com.beiing.tianshuai.tianshuai.dongtai;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.DynamicAdapter;
import com.beiing.tianshuai.tianshuai.anim.LikeAnimator;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.common.ui.ReportActivity;
import com.beiing.tianshuai.tianshuai.dongtai.presenter.DynamicPresenter;
import com.beiing.tianshuai.tianshuai.dongtai.ui.DynamicMessageActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicDetailActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicPublishActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicViewImpl;
import com.beiing.tianshuai.tianshuai.entity.DynamicAddRelayCommentBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicAddReplyBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicCommentAndReplyBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicCommentBean;
import com.beiing.tianshuai.tianshuai.entity.FollowBean;
import com.beiing.tianshuai.tianshuai.entity.NoticeMarksBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DisplayUtil;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 动态列表
 *
 * @author Jinni
 * @date 2017/7/17
 */

public class DynamicFragment extends BaseFragment implements DynamicViewImpl, ActionSheet.OnSheetItemClickListener {

    @BindView(R.id.content)
    RelativeLayout mContent;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_ib_new_msg)
    ImageButton mToolbarIbNewMsg;
    @BindView(R.id.toolbar_ib_publish)
    ImageButton ivPublish;
    @BindView(R.id.rv_dynamics)
    RecyclerView mRvDynamics;
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;
    @BindView(R.id.dynamic_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.dynamic_footer)
    ClassicsFooter mRefreshFooter;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;
    @BindView(R.id.dynamic_detail_edit)
    EditText mCommentEdit;
    @BindView(R.id.dynamic_detail_send)
    TextView tvSend;
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyboard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;

    private static final int PAGE_SIZE = 15;
    private static int mLastItemPosition = 0;

    /**
     * 是否加载全部
     */
    private static boolean isLoadFinish;

    /**
     * 是否第一次加载
     */
    private boolean isFirstLoad = true;

    /**
     *  滑动监听，是否加载
     */
    private boolean sIsScrolling;
    private Context mContext;
    private static DynamicPresenter mPresenter;
    private DynamicAdapter mAdapter;
    private static List<DynamicBean.DataBean.DynamicsBean> mDynamicsBeanList;
    private static String uid;
    private int mPosition;
    private DynamicBean.DataBean.DynamicsBean mBean;
    private RxBus rxBus;
    private InputMethodManager imm;
    private PopupMenu mPopupMenu;
    private int retryConnect;
    private EmotionCompleteFragment emotionCompleteFragment;
    private GlobalOnItemClickManagerUtils globalOnItemClickManager;
    private static final String TAG = "DynamicFragment";

    /**
     * 动态有新消息提醒时展示point作为提醒
     */
    @SuppressLint("StaticFieldLeak")
    private static TextView mNewMessagePoint;
    private LinearLayoutManager linearLayoutManager;
    private int itemToInputDistance;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dongtai;
    }

    @Override
    protected void init(View mView) {
        mContext = getActivity();
        uid = UserInfoBean.getUid(mContext);
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        initToolbar();
        initRefreshLayout();
        initRecyclerView();
        initListener();
        initPresenter();
        initRxBus();
        initEmotionMainFragment();
    }

    private void initEmotionMainFragment() {
        globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext.getApplicationContext());
        globalOnItemClickManager.attachToEditText(mCommentEdit);
        emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction;
        if (getActivity() != null) {
            transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
            transaction.commit();
        }
    }

    public static void setNewMessagePointState() {
        DisposableObserver<NoticeMarksBean> observer = new DisposableObserver<NoticeMarksBean>() {
            @Override
            public void onNext(@NonNull NoticeMarksBean bean) {
                if (bean.getCode() == 200) {
                    int replyCount = bean.getData().getComment();
                    int praiseCount = bean.getData().getThing();
                    int sumCount = replyCount + praiseCount;
                    if (sumCount > 0) {
                        mNewMessagePoint.setText(String.valueOf(sumCount));
                        mNewMessagePoint.setVisibility(View.VISIBLE);
                    } else {
                        mNewMessagePoint.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.e("获取动态新消息数量失败 " + e.getMessage(), "MainActivity");
            }

            @Override
            public void onComplete() {
                LogUtils.i("获取动态新消息数量完成", "MainActivity");
            }
        };

        DataManager.getNoticeMarksResult(uid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void initToolbar() {
        toolbarTitle.setText("动态");
        mNewMessagePoint = mView.findViewById(R.id.tv_new_message_point);
    }

    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSrlMyRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mLastItemPosition = 0;
                isLoadFinish = false;
                mPresenter.getDynamicsResult(UserInfoBean.getUid(mContext), mLastItemPosition, PAGE_SIZE, null, null, 1);
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinish) {
                    mPresenter.getDynamicsResult(UserInfoBean.getUid(mContext), mLastItemPosition, PAGE_SIZE, DynamicAdapter.dynamicId, DynamicAdapter.relayDynamicId, 0);
                } else {
                    showShortText("已加载全部内容");
                    mSrlMyRefreshLayout.finishLoadmore();
                }
            }
        });
    }

    private void initRecyclerView() {
        mDynamicsBeanList = new ArrayList<>();
        mAdapter = new DynamicAdapter(mContext, mDynamicsBeanList);
        mAdapter.setHasStableIds(true);
        linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvDynamics.setNestedScrollingEnabled(false);
        mRvDynamics.setLayoutManager(linearLayoutManager);
        ((SimpleItemAnimator) mRvDynamics.getItemAnimator()).setSupportsChangeAnimations(false);
        mRvDynamics.setAdapter(mAdapter);
    }

    private void initListener() {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect r = new Rect();
                    View view = getActivity().getWindow().getDecorView();
                    view.getWindowVisibleDisplayFrame(r);
                    // 底部导航栏高度
                    int bottomNavigationBarHeight = DisplayUtil.dip2px(mContext, 51);
                    int navigationBarHeight;
                    if (DisplayUtil.isNavigationBarShow(mContext)) {
                        // 底部虚拟按键高度
                        navigationBarHeight = DisplayUtil.getNavigationBarHeight(mContext);
                    } else {
                        navigationBarHeight = 0;
                    }
                    // 软键盘弹起
                    if (getActivity().getWindow().getDecorView().getHeight() - r.bottom > navigationBarHeight) {
                        itemToInputDistance = r.bottom - llComment.getHeight() - bottomNavigationBarHeight;
                    } else {
                        llComment.setTranslationY(0);
                    }
                }
            });
        }
        //recycleView滑动监听
        mRvDynamics.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    sIsScrolling = true;
                    Glide.with(DynamicFragment.this).pauseRequests();
                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (sIsScrolling == true) {
                        Glide.with(DynamicFragment.this).resumeRequests();
                    }
                    sIsScrolling = false;

                }
            }
        });

        mToolbarIbNewMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(uid)) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    startActivity(new Intent(mContext, DynamicMessageActivity.class));
                }
            }
        });

        // 条目评论按钮点击事件
        mAdapter.setOnItemCommentClickListener(new DynamicAdapter.OnItemCommentClickListener() {
            @Override
            public void onItemCommentClickListener(DynamicBean.DataBean.DynamicsBean bean, int position) {
                mAdapter.setOnItemClickListener(null);
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    llComment.setVisibility(View.VISIBLE);
                    mCommentEdit.setHint("评论...");
                    mCommentEdit.setFocusable(true);
                    mCommentEdit.setFocusableInTouchMode(true);
                    mCommentEdit.requestFocus();
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mEmotionLayout.setVisibility(View.GONE);
                    ivFace.setVisibility(View.VISIBLE);
                    ivKeyboard.setVisibility(View.GONE);
                    int type;
                    if (bean.getFormUid() == null) {
                        type = 0;
                    } else {
                        type = 1;
                    }
                    tvSend.setOnClickListener(new DynamicCommentSendClickListener(
                            mPresenter,
                            bean,
                            mCommentEdit,
                            mContext,
                            position,
                            type,
                            llComment
                    ));
                    int itemBottom = linearLayoutManager.findViewByPosition(position).getBottom();
                    if (itemToInputDistance != 0) {
                        mRvDynamics.scrollBy(0, itemBottom - itemToInputDistance + DisplayUtil.dip2px(mContext, 12));
                    }
                }
            }
        });

        mAdapter.setOnItemViewClickListener(new DynamicAdapter.OnItemViewClickListener() {
            @Override
            public void onItemViewClick(View view, int position) {
                switch (view.getId()) {
                    // 点击头像
                    case R.id.ll_user_avatar:
                        mAdapter.setOnItemClickListener(null);
                        Intent intent = new Intent(getActivity(), NewPersonalIndexActivity.class);
                        if (mDynamicsBeanList.get(position).getFormUid() != null) {
                            intent.putExtra("uid", mDynamicsBeanList.get(position).getFormUid());
                        } else {
                            intent.putExtra("uid", mDynamicsBeanList.get(position).getUid());
                        }
                        startActivity(intent);
                        break;
                    case R.id.tv_check_comment:
                        Intent intent1 = new Intent();
                        if (mDynamicsBeanList.get(position).getFormUid() != null) {
                            intent1.setClass(mContext, DynamicRelayDetailActivity.class);
                        } else {
                            intent1.setClass(mContext, DynamicDetailActivity.class);
                        }
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("dynamic", mDynamicsBeanList.get(position));

                        // 传递动态id，让详情页面重新请求数据
                        intent1.putExtra("dynamic_id", mDynamicsBeanList.get(position).getIdOne());
                        intent1.putExtra("dynamic_position", position);
                        intent1.putExtras(bundle);
                        startActivity(intent1);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onMoreClick(View view, int position, DynamicBean.DataBean.DynamicsBean bean) {
                if (TextUtils.isEmpty(uid)) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
//                    showDynamicMenu(mContext, position, bean);
                    mPresenter.isFollowed(uid, bean, position);
                }
            }

            @Override
            public void onItemClick(View view, int position, DynamicBean.DataBean.DynamicsBean bean) {
                if (bean != null) {
                    Intent intent = new Intent();
                    if (bean.getFormUid() != null) {
                        intent.setClass(mContext, DynamicRelayDetailActivity.class);
                    } else {
                        intent.setClass(mContext, DynamicDetailActivity.class);
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("dynamic", bean);
                    // 传递动态id，让详情页面重新请求数据
                    intent.putExtra("dynamic_id", bean.getIdOne());
                    intent.putExtra("dynamic_position", position);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }

        });

        // 动态列表上头像的点击事件
        mAdapter.setOnUserAvatarClickListener(new DynamicAdapter.OnUserAvatarClickListener() {
            @Override
            public void onUserAvatarClick(String uid) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", uid);
                startActivity(intent);
            }
        });

        // 动态列表上的删除点击事件
        mAdapter.setOnDeleteClickListener(new DynamicAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(final DynamicBean.DataBean.DynamicsBean bean, final int position) {
                if (TextUtils.isEmpty(bean.getFormUid())) {
                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                            "确定要删除这条动态么？",
                            new CustomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        LogUtils.i("tabletype", "删除");
                                        mPresenter.deleteDynamic(uid, bean.getIdOne(), position);   //删除动态
                                        showShortText("删除成功");
                                        dialog.dismiss();
                                    } else {
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示");
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                } else {
                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                            "确定要删除这条动态么？",
                            new CustomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        mPresenter.deleteRelay(uid, bean.getIdOne(), position);
                                        showShortText("删除成功");
                                        dialog.dismiss();
                                    } else {
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示");
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                }
            }
        });

        // 转发
        mAdapter.setOnReprintClickListener(new DynamicAdapter.OnReprintClickListener() {
            @Override
            public void onReprintClick(DynamicBean.DataBean.DynamicsBean bean, int position) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    Intent forwardIntent = new Intent();
                    forwardIntent.setClass(mContext, DynamicForwardActivity.class);
                    Bundle forwardBundle = new Bundle();
                    forwardBundle.putSerializable("dynamic", bean);
                    forwardIntent.putExtras(forwardBundle);
                    startActivity(forwardIntent);
                }
            }
        });

        // 点赞
        mAdapter.setOnLikeClickListener(new DynamicAdapter.OnLikeClickListener() {
            @Override
            public void onLikeClick(View view, int position, DynamicBean.DataBean.DynamicsBean bean, TextView addOneTv) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    DynamicBean.DataBean.DynamicsBean.ThingIdBean thingIdBean = new DynamicBean.DataBean.DynamicsBean.ThingIdBean();
                    thingIdBean.setId(uid);
                    thingIdBean.setName(UserInfoBean.getNickName(mContext));
                    thingIdBean.setPhoto(UserInfoBean.getAvatar(mContext));

                    mAdapter.setOnItemClickListener(null);
                    if ("0".equals(bean.getTableType())) {
                        mPresenter.praiseRelay(UserInfoBean.getUid(mContext), bean.getIdOne(), bean.getId(), bean.getFormUid(), position);
                    } else {
                        mPresenter.praiseDynamic(UserInfoBean.getUid(mContext), bean.getIdOne(), bean.getUid(), position);
                    }
                    boolean isLiked = bean.getIsThing() == 1;//是否点赞
                    TextView likeView = (TextView) view;
                    Integer likeNum = Integer.valueOf(likeView.getText().toString());
                    if (isLiked) {
                        LikeAnimator.disLikeAnimator(mContext, likeView);
                        likeNum--;
                        int removePosition = 0;
                        for (DynamicBean.DataBean.DynamicsBean.ThingIdBean thingIdBean1 : bean.getThingId()) {
                            if (thingIdBean1.getId().equals(thingIdBean.getId())) {
                                removePosition = bean.getThingId().indexOf(thingIdBean1);
                            }
                        }
                        bean.getThingId().remove(removePosition);
                    } else {
                        LikeAnimator.thumbAnimator(mContext, likeView);
                        LikeAnimator.addOneTextAnimator(mContext, addOneTv);
                        likeNum++;
                        bean.getThingId().add(0, thingIdBean);
                    }
                    likeView.setText(String.valueOf(likeNum));
                    bean.setThing(String.valueOf(likeNum));

                    // 修改数据源
                    int isThing = bean.getIsThing();
                    if (isThing == 1) {
                        bean.setIsThing(0);
                    } else {
                        bean.setIsThing(1);
                    }
                    mAdapter.notifyItemChanged(position);
                }
            }
        });

        mAdapter.setOnTextClickListener(new DynamicAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(View view, int dynamicPosition, int commentPosition, int textPosition, DynamicCommentAndReplyBean commentAndReplyBean) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                switch (textPosition) {
                    case 0:
                        intent.putExtra("uid", commentAndReplyBean.getUid());
                        break;
                    case 1:
                        intent.putExtra("uid", commentAndReplyBean.getTo_uid());
                        break;default:
                }
                startActivity(intent);
            }
        });


        // 评论回复点击事件
        mAdapter.setOnCommentClickListener(new DynamicAdapter.OnCommentClickListener() {

            @Override
            public void onItemClick(View view, int dynamicPosition, int commentPosition,
                                    DynamicCommentAndReplyBean commentAndReplyBean,
                                    DynamicBean.DataBean.DynamicsBean dynamicBean) {

                // 点击评论回复时弹出输入框，传递评论对象至点击事件
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    String tableType = commentAndReplyBean.getTable_type();
                    int type = 0;
                    switch (tableType) {
                        case "0":
                            type = 2;
                            break;
                        case "1":
                            type = 3;
                            break;
                            default:
                    }
                    tvSend.setOnClickListener(new DynamicCommentSendClickListener(
                            mPresenter,
                            commentAndReplyBean,
                            mCommentEdit,
                            mContext,
                            commentPosition,
                            type,
                            llComment,
                            dynamicBean,
                            dynamicPosition
                    ));
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    llComment.setVisibility(View.VISIBLE);
                    mCommentEdit.requestFocus();
                    mCommentEdit.setHint("回复" + commentAndReplyBean.getF_name());
                }
            }
        });

        // 发布动态
        ivPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, DynamicPublishActivity.class));
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });

        mCommentEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //有文字内容
                if (editable.length() > 0 && !"".equals(editable.toString().trim())) {
                    tvSend.setBackgroundResource(R.drawable.publish_blue);
                    //没有文字内容
                } else {
                    tvSend.setBackgroundResource(R.drawable.publish_gray);
                }
            }
        });

        mCommentEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyboard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                return false;
            }
        });

        mRvDynamics.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (llComment != null) {
                    llComment.setVisibility(View.GONE);
                    imm.hideSoftInputFromWindow(llComment.getWindowToken(), 0);
                    mEmotionLayout.setVisibility(View.GONE);
                    mCommentEdit.setText("");
                }
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyboard.setVisibility(View.VISIBLE);
                imm.hideSoftInputFromWindow(llComment.getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
            }
        });

        ivKeyboard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivKeyboard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                mEmotionLayout.setVisibility(View.GONE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }

    @Override
    public void showCenterMenu(FollowBean followBean, final DynamicBean.DataBean.DynamicsBean bean, final int position) {
        final Dialog dialog = new Dialog(getActivity());
        //动态item 更多菜单
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_dynamic_list, null);
        TextView tv_collect = view.findViewById(R.id.tv_collect);
        final TextView tv_follow = view.findViewById(R.id.tv_follow);
        TextView tv_shield = view.findViewById(R.id.tv_shield);
        TextView tv_report = view.findViewById(R.id.tv_report);

        //暂时隐藏 收藏与举报
        tv_collect.setVisibility(View.GONE);

        if (followBean.getCode() == 0) {
            tv_follow.setText("关注");
        } else {
            tv_follow.setText("取消关注");
        }
        final String publisherUid = bean.getFormUid() == null ? bean.getUid() : bean.getFormUid();
        final boolean isMine = publisherUid.equals(uid);
        if (isMine) {
            tv_shield.setText("删除此条");
        } else {
            tv_shield.setText("屏蔽此条");
        }
        //收藏
        tv_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        //关注
        tv_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.setFollowed(uid, publisherUid);
                if (tv_follow.getText().equals("关注")) {
                    tv_follow.setText("取消关注");
                    showShortText("关注成功");
                } else {
                    tv_follow.setText("关注");
                    showShortText("已取消关注");
                }
                dialog.dismiss();
            }
        });
        //屏蔽or删除
        tv_shield.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                if (isMine) {        //删除
                    if (bean.getTableType().equals("1")) {    //删除原创
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要删除这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            LogUtils.i("tabletype", "删除");
                                            mPresenter.deleteDynamic(uid, bean.getIdOne(), position);   //删除动态
                                            showShortText("删除成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    } else {                            //删除转发
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要删除这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            mPresenter.deleteRelay(uid, bean.getIdOne(), position);
                                            showShortText("删除成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    }
                } else {            //屏蔽
                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                            "确定要屏蔽这条动态么？",
                            new CustomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        mPresenter.shieldDynamic(uid, bean.getIdOne(), position);
                                        showShortText("屏蔽成功");
                                        dialog.dismiss();
                                    } else {
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示");
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                }
            }
        });
        //举报
        tv_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ReportActivity.class);
                intent.putExtra("currency_id", bean.getIdOne());
                intent.putExtra("tid", "1");
                startActivity(intent);
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        dialog.show();
    }

    private void showPopupWindow(View view, int position, final DynamicCommentAndReplyBean commentAndReplyBean) {
        mPopupMenu = new PopupMenu(mContext, view, Gravity.RIGHT);
        mPopupMenu.getMenuInflater().inflate(R.menu.comment_click_menu, mPopupMenu.getMenu());
        mPopupMenu.show();
        mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.item_copy:
                        ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                        try {
                            cm.setText(URLDecoder.decode(commentAndReplyBean.getContent(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        showShortText("已复制");
                        break;
                    case R.id.item_delete:

                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void initPresenter() {
        mPresenter = new DynamicPresenter(this);
        mPresenter.getDynamicsResult(uid, 0, PAGE_SIZE, null, null, 1);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
        }
    }

    @Override
    public void onResume() {
        uid = UserInfoBean.getUid(mContext);
        initEmotionMainFragment();
        setNewMessagePointState();
        super.onResume();
    }

    /**
     * 显示动态列表
     *
     * @param dynamicBean 动态
     */
    @Override
    public void showDynamicList(DynamicBean dynamicBean) {
        List<DynamicBean.DataBean.DynamicsBean> dynamics = dynamicBean.getData().getDynamics();
        int size = dynamics.size();
        if (size == 0) {
            isLoadFinish = true;
            showShortText("已加载全部内容");
        } else if (size < PAGE_SIZE) {
            isLoadFinish = true;
            mLastItemPosition += size;
            mDynamicsBeanList.addAll(dynamics);
            mAdapter.notifyDataSetChanged();
            showShortText("已加载全部内容");
        } else {
            isLoadFinish = false;
            mLastItemPosition += size;
            mDynamicsBeanList.addAll(dynamics);
            mAdapter.notifyDataSetChanged();
        }
        if (mSrlMyRefreshLayout != null && (mSrlMyRefreshLayout.isRefreshing() || mSrlMyRefreshLayout.isLoading())) {
            mSrlMyRefreshLayout.finishRefresh();
            mSrlMyRefreshLayout.finishLoadmore();
        }
    }

    /**
     * 下拉刷新 替换数据
     *
     * @param dynamicBean 动态信息
     */
    @Override
    public void refreshDynamicList(DynamicBean dynamicBean) {
        List<DynamicBean.DataBean.DynamicsBean> dynamics = dynamicBean.getData().getDynamics();
        int size = dynamics.size();
        mDynamicsBeanList.clear();
        if (size == 0) {
            isLoadFinish = true;
        } else if (size < PAGE_SIZE) {
            isLoadFinish = true;
            mLastItemPosition += size;
            mDynamicsBeanList.addAll(dynamics);
            mAdapter.update();
        } else {
            isLoadFinish = false;
            mLastItemPosition += size;
            mDynamicsBeanList.addAll(dynamics);
            mAdapter.update();
        }
        if (mSrlMyRefreshLayout != null && (mSrlMyRefreshLayout.isRefreshing() || mSrlMyRefreshLayout.isLoading())) {
            mSrlMyRefreshLayout.finishRefresh();
            mSrlMyRefreshLayout.finishLoadmore();
        }
    }

    /**
     * 更新动态  屏蔽/删除
     *
     * @param position 操作数据所在位置
     */
    @Override
    public void updateDynamic(int position) {
        mLastItemPosition--;
        mDynamicsBeanList.remove(position);
        mAdapter.removeData(position);
        //当删除至屏幕内的内容无法填满屏幕时重新获取动态列表
        if (mAdapter.getItemCount() < 15) {
            mLastItemPosition = 0;
            mDynamicsBeanList.clear();
            mPresenter.getDynamicsResult(uid, mLastItemPosition, PAGE_SIZE, null, null, 1);
            mRefreshHeader.onFinish(mSrlMyRefreshLayout, true);
        }
    }

    //获取动态列表请求出错
    @Override
    public void requestError(int type) {
        switch (type) {
            case 0:
                if (retryConnect < 5) {
                    retryConnect++;
                    mPresenter.getDynamicsResult(UserInfoBean.getUid(mContext), mLastItemPosition, PAGE_SIZE, DynamicAdapter.dynamicId, DynamicAdapter.relayDynamicId, 0);
                } else {
                    retryConnect = 0;
//                    showShortText("数据获取错误，请检查您的网络");
                    mRefreshHeader.onFinish(mSrlMyRefreshLayout, false);
                    if (mSrlMyRefreshLayout != null && (mSrlMyRefreshLayout.isRefreshing() || mSrlMyRefreshLayout.isLoading())) {
                        mSrlMyRefreshLayout.finishRefresh(false);
                        mSrlMyRefreshLayout.finishLoadmore(false);
                    }
                }
                break;
            case 1:
                if (retryConnect < 5) {
                    retryConnect++;
                    mPresenter.getDynamicsResult(UserInfoBean.getUid(mContext), 0, PAGE_SIZE, null, null, 1);
                } else {
                    retryConnect = 0;
//                    showShortText("数据获取错误，请检查您的网络");
                    mRefreshHeader.onFinish(mSrlMyRefreshLayout, false);
                    if (mSrlMyRefreshLayout != null && (mSrlMyRefreshLayout.isRefreshing() || mSrlMyRefreshLayout.isLoading())) {
                        mSrlMyRefreshLayout.finishRefresh(false);
                        mSrlMyRefreshLayout.finishLoadmore(false);
                    }
                }
                break;
        }
    }

    /**
     * 显示错误
     */
    @Override
    public void showError(int errorType) {
        switch (errorType) {
            case 0:                         //获取动态列表错误
                break;
            case 1:                         //动态点赞失败
                showShortText("点赞失败，请稍后重试");
                break;
            case 2:                         //转发动态点赞失败
                showShortText("点赞失败，请稍后重试");
                break;
            case 3:                         //屏蔽失败
                showShortText("屏蔽失败，请稍后重试");
                break;
            case 4:                         //删除动态失败
                showShortText("删除失败，请稍后重试");
                break;
            case 5:                         //删除转发动态失败
                showShortText("删除失败，请稍后重试");
                break;
        }
        if (mSrlMyRefreshLayout != null && mSrlMyRefreshLayout.isRefreshing()) {
            mSrlMyRefreshLayout.finishRefresh();
        }
        if (mSrlMyRefreshLayout != null && mSrlMyRefreshLayout.isLoading()) {
            mSrlMyRefreshLayout.finishLoadmore();
        }
    }

    /**
     * 显示加载进度条
     */
    @Override
    public void showProgress() {
        if (isFirstLoad) {
            CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
            isFirstLoad = false;
        }
    }

    /**
     * 隐藏进度条
     */
    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }


    /**
     * 添加评论结果
     *
     * @param dynamicCommentBean 评论返回实体类
     * @param position           评论的条目位置
     * @param dynamicBean        当前所评论的动态
     */
    @Override
    public void showCommentResult(DynamicCommentBean dynamicCommentBean, String time, int position, DynamicBean.DataBean.DynamicsBean dynamicBean) {
        dynamicBean.setComment(String.valueOf(dynamicCommentBean.getData().getCount()));
        DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean = new DynamicBean.DataBean.DynamicsBean.CommentTextBean();

        commentTextBean.setId(dynamicCommentBean.getData().getNumber());
        commentTextBean.setUid(uid);
        commentTextBean.setContent(dynamicCommentBean.getData().getContent());
        commentTextBean.setCreateTime(time);
        commentTextBean.setName(UserInfoBean.getNickName(mContext));
        commentTextBean.setTableType("0");

        dynamicBean.getCommentText().add(commentTextBean);
        mAdapter.notifyItemChanged(position);

    }

    @Override
    public void showRelayCommentResult(DynamicAddRelayCommentBean relayCommentBean, String rid, String content, int position, DynamicBean.DataBean.DynamicsBean dynamicBean) {
//        mDynamicsBeanList.get(position).setComment(relayCommentBean.getData().getCount() + "");
//        DynamicCommentAndReplyBean CARBean = new DynamicCommentAndReplyBean();
//        CARBean.setDid(rid);
//        CARBean.setId(relayCommentBean.getData().getNumber());
//        CARBean.setUid(uid);
//        CARBean.setContent(content);
//        CARBean.setCreate_time(System.currentTimeMillis() / 1000 + "");
//        CARBean.setF_name(UserInfoBean.getNickName(mContext));
//        CARBean.setTable_type("1");

        dynamicBean.setComment(String.valueOf(relayCommentBean.getData().getCount()));
        DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean = new DynamicBean.DataBean.DynamicsBean.CommentTextBean();
        commentTextBean.setId(relayCommentBean.getData().getNumber());
        commentTextBean.setUid(uid);
        commentTextBean.setContent(content);
        commentTextBean.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        commentTextBean.setName(UserInfoBean.getNickName(mContext));
        commentTextBean.setTableType("1");
        dynamicBean.getCommentText().add(commentTextBean);
        mAdapter.notifyItemChanged(position);
    }

    @Override
    public void showAddReplyResult(DynamicCommentAndReplyBean dynamicCommentAndReplyBean,
                                   int dynamicPosition,
                                   DynamicBean.DataBean.DynamicsBean dynamicBean,
                                   DynamicAddReplyBean bean, String content, String did,
                                   int position) {

        dynamicBean.setComment(String.valueOf(bean.getData().getCount()));

        DynamicBean.DataBean.DynamicsBean.ReplyTextBean replyTextBean = new DynamicBean.DataBean.DynamicsBean.ReplyTextBean();
        replyTextBean.setId(bean.getData().getNumber());
        replyTextBean.setDid(did);
        replyTextBean.setForm_uid(UserInfoBean.getUid(mContext));
        replyTextBean.setTo_uid(dynamicCommentAndReplyBean.getUid());
        replyTextBean.setContent(content);
        replyTextBean.setCreate_time(String.valueOf(System.currentTimeMillis() / 1000));
        replyTextBean.setfName(UserInfoBean.getNickName(mContext));
        replyTextBean.settName(dynamicCommentAndReplyBean.getF_name());
        replyTextBean.setTable_type("2");

        dynamicBean.getReplyText().add(replyTextBean);
        mAdapter.notifyItemChanged(dynamicPosition);
    }

    @Override
    public void showAddRelayReplyResult(DynamicCommentAndReplyBean dynamicCommentAndReplyBean,
                                        int dynamicPosition,
                                        DynamicBean.DataBean.DynamicsBean dynamicBean,
                                        DynamicAddReplyBean bean, String content, String rid,
                                        int position) {

        dynamicBean.setComment(String.valueOf(bean.getData().getCount()));

        DynamicBean.DataBean.DynamicsBean.ReplyTextBean replyTextBean = new DynamicBean.DataBean.DynamicsBean.ReplyTextBean();
        replyTextBean.setId(bean.getData().getNumber());
        replyTextBean.setDid(rid);
        replyTextBean.setForm_uid(UserInfoBean.getUid(mContext));
        replyTextBean.setTo_uid(dynamicCommentAndReplyBean.getUid());
        replyTextBean.setContent(content);
        replyTextBean.setCreate_time(String.valueOf(System.currentTimeMillis() / 1000));
        replyTextBean.setfName(UserInfoBean.getNickName(mContext));
        replyTextBean.settName(dynamicCommentAndReplyBean.getF_name());
        replyTextBean.setTable_type("3");

        dynamicBean.getReplyText().add(replyTextBean);
        mAdapter.notifyItemChanged(dynamicPosition);
    }

    /**
     * 发布动态(包括转发)后刷新动态列表
     */
    public static void updateDynamicList() {
        if (mDynamicsBeanList != null && mPresenter != null) {
            mLastItemPosition = 0;
            mDynamicsBeanList.clear();
            mPresenter.getDynamicsResult(uid, mLastItemPosition, PAGE_SIZE, null, null, 1);
        }
    }

    public void showDynamicMenu(Context context, int position, DynamicBean.DataBean.DynamicsBean bean) {
        mPosition = position;
        mBean = bean;
        ActionSheet actionSheet = new ActionSheet(context);
//        Log.i(TAG, uid);
        if (bean.getFormUid() == null) {          //判断是否是转发
            if (bean.getUid().equals(uid)) {                 //判断是否是自己发布的动态
                actionSheet.builder()
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("删除", ActionSheet.SheetItemColor.Blue, this)
                        .show();
            } else {
                actionSheet.builder()
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("屏蔽", ActionSheet.SheetItemColor.Blue, this)
                        .show();
            }
        } else {
            if (bean.getFormUid().equals(uid)) {
                actionSheet.builder()
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("删除", ActionSheet.SheetItemColor.Blue, this)
                        .show();
            } else {
                actionSheet.builder()
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("屏蔽", ActionSheet.SheetItemColor.Blue, this)
                        .show();
            }
        }

    }

    @Override
    public void onClick(int which) {
        if (mBean.getTableType().equals("1")) {        //1为原创内容
            switch (which) {
                case 1:
                    if (mBean.getUid().equals(uid)) {      //自己发布的
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要删除这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            mPresenter.deleteDynamic(uid, mBean.getIdOne(), mPosition);   //删除动态
                                            showShortText("删除成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    } else {
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要屏蔽这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            mPresenter.shieldDynamic(uid, mBean.getIdOne(), mPosition);
                                            showShortText("删除成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    }
                    break;
            }
        } else {                                                                //0为转发内容
            switch (which) {
                case 1:
                    if (mBean.getFormUid().equals(uid)) {      //自己转发的
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要删除这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            mPresenter.deleteRelay(uid, mBean.getIdOne(), mPosition);
                                            showShortText("删除成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    } else {
                        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                "确定要屏蔽这条动态么？",
                                new CustomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            mPresenter.shieldDynamic(uid, mBean.getIdOne(), mPosition);
                                            showShortText("屏蔽成功");
                                            dialog.dismiss();
                                        } else {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示");
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                    }
                    break;
            }
        }
    }

    private void initRxBus() {
        rxBus = RxBus.getInstanceBus();
        final DynamicBean.DataBean.DynamicsBean.ThingIdBean thingIdBean = new DynamicBean.DataBean.DynamicsBean.ThingIdBean();
        thingIdBean.setPhoto(UserInfoBean.getAvatar(mContext));
        thingIdBean.setId(uid);
        thingIdBean.setName(UserInfoBean.getNickName(mContext));
        registerRxBus(MsgEvent.class, new Consumer<MsgEvent>() {
            @Override
            public void accept(@NonNull MsgEvent msgEvent) throws Exception {
                //根据事件类型进行处理
                if (TextUtils.equals(msgEvent.getType(), "dynamic_detail_praise")) {
                    if ((int) msgEvent.getData() == 200) {                              //点赞成功
                        int newThing = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getThing()) + 1;
                        mDynamicsBeanList.get(msgEvent.getPosition()).setThing(newThing + "");
                        mDynamicsBeanList.get(msgEvent.getPosition()).setIsThing(1);
                        mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().add(0, thingIdBean);
                        mAdapter.notifyItemChanged(msgEvent.getPosition());
                    } else if ((int) msgEvent.getData() == 201) {                       //取消点赞成功
                        int newThing = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getThing()) - 1;
                        mDynamicsBeanList.get(msgEvent.getPosition()).setThing(newThing + "");
                        mDynamicsBeanList.get(msgEvent.getPosition()).setIsThing(0);
                        int removePosition = -1;
                        for (DynamicBean.DataBean.DynamicsBean.ThingIdBean thingId : mDynamicsBeanList.get(msgEvent.getPosition()).getThingId()) {
                            if (thingId.getId().equals(uid)) {
                                removePosition = mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().indexOf(thingId);
                            }
                        }
                        if (removePosition != -1) {
                            mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().remove(removePosition);
                        }
                        mAdapter.notifyItemChanged(msgEvent.getPosition());
                    }
                } else if (TextUtils.equals(msgEvent.getType(), "dynamic_detail_comment")) {
                    int newCommentNum = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getComment()) + 1;
                    mDynamicsBeanList.get(msgEvent.getPosition()).setComment(newCommentNum + "");
                    DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean = new DynamicBean.DataBean.DynamicsBean.CommentTextBean();
                    commentTextBean.setContent(((DynamicCommentBean) msgEvent.getData()).getData().getContent());
                    commentTextBean.setName(UserInfoBean.getNickName(mContext));
                    commentTextBean.setUid(uid);
                    commentTextBean.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
                    commentTextBean.setTableType("0");
                    mDynamicsBeanList.get(msgEvent.getPosition()).getCommentText().add(0, commentTextBean);
                    mAdapter.notifyItemChanged(msgEvent.getPosition());
                } else if (TextUtils.equals(msgEvent.getType(), "dynamic_detail_comment_delete")) {
                    int dynamicPosition = msgEvent.getPosition();
                    int newCommentNum = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getComment()) - 1;
                    mDynamicsBeanList.get(dynamicPosition).setComment(newCommentNum + "");

                    //移除对应的评论
                    int deletePosition = -1;
                    for (DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean : mDynamicsBeanList.get(dynamicPosition).getCommentText()) {
                        if (commentTextBean.getId().equals(msgEvent.getData())) {
                            deletePosition = mDynamicsBeanList.get(dynamicPosition).getCommentText().indexOf(commentTextBean);
                        }
                    }
                    if (deletePosition != -1) {
                        mDynamicsBeanList.get(dynamicPosition).getCommentText().remove(deletePosition);
                    }

                    //移除该评论下的回复
                    int deleteReplyPosition = -1;
                    if (!mDynamicsBeanList.get(dynamicPosition).getReplyText().isEmpty()) {
                        for (DynamicBean.DataBean.DynamicsBean.ReplyTextBean replyTextBean : mDynamicsBeanList.get(dynamicPosition).getReplyText()) {
                            if (replyTextBean.getCid().equals(msgEvent.getData())) {
                                deleteReplyPosition = mDynamicsBeanList.get(dynamicPosition).getReplyText().indexOf(replyTextBean);
                            }
                        }
                        if (deleteReplyPosition != -1) {
                            mDynamicsBeanList.get(dynamicPosition).getReplyText().remove(deleteReplyPosition);
                        }
                    }
                    mAdapter.notifyItemChanged(dynamicPosition);

                } else if (TextUtils.equals(msgEvent.getType(), "转发点赞")) {
                    if ((int) msgEvent.getData() == 200) {
                        int newThing = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getThing()) + 1;
                        mDynamicsBeanList.get(msgEvent.getPosition()).setThing(newThing + "");
                        mDynamicsBeanList.get(msgEvent.getPosition()).setIsThing(1);
                        mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().add(0, thingIdBean);
                        mAdapter.notifyItemChanged(msgEvent.getPosition());
                    } else if ((int) msgEvent.getData() == 201) {
                        int newThing = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getThing()) - 1;
                        mDynamicsBeanList.get(msgEvent.getPosition()).setThing(newThing + "");
                        mDynamicsBeanList.get(msgEvent.getPosition()).setIsThing(0);
                        int deletePosition = -1;
                        for (DynamicBean.DataBean.DynamicsBean.ThingIdBean thingId : mDynamicsBeanList.get(msgEvent.getPosition()).getThingId()) {
                            if (thingId.getId().equals(uid)) {
                                deletePosition = mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().indexOf(thingId);
                            }
                        }
                        if (deletePosition != -1) {
                            mDynamicsBeanList.get(msgEvent.getPosition()).getThingId().remove(deletePosition);
                        }
                        mAdapter.notifyItemChanged(msgEvent.getPosition());
                    }
                } else if (TextUtils.equals(msgEvent.getType(), "dynamicRelay_detail_comment")) {
                    int newComment = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getComment()) + 1;
                    mDynamicsBeanList.get(msgEvent.getPosition()).setComment(newComment + "");
                    DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean = new DynamicBean.DataBean.DynamicsBean.CommentTextBean();
                    commentTextBean.setUid(uid);
                    commentTextBean.setName(UserInfoBean.getNickName(mContext));
                    commentTextBean.setTableType("1");
                    commentTextBean.setContent(msgEvent.getData().toString());
                    commentTextBean.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
                    mAdapter.notifyItemChanged(msgEvent.getPosition());
                } else if (TextUtils.equals(msgEvent.getType(), "dynamicRelay_detail_comment_delete")) {
                    int dynamicPosition = msgEvent.getPosition();
                    int newComment = Integer.parseInt(mDynamicsBeanList.get(msgEvent.getPosition()).getComment()) - 1;
                    mDynamicsBeanList.get(dynamicPosition).setComment(newComment + "");
                    int deletePosition = -1;
                    for (DynamicBean.DataBean.DynamicsBean.CommentTextBean commentTextBean : mDynamicsBeanList.get(dynamicPosition).getCommentText()) {
                        if (commentTextBean.getId().equals(msgEvent.getData())) {
                            deletePosition = mDynamicsBeanList.get(dynamicPosition).getCommentText().indexOf(commentTextBean);
                        }
                    }
                    if (deletePosition != -1) {
                        mDynamicsBeanList.get(dynamicPosition).getCommentText().remove(deletePosition);
                    }

                    int deleteReplyPosition = -1;
                    if (!mDynamicsBeanList.get(dynamicPosition).getReplyText().isEmpty()) {
                        for (DynamicBean.DataBean.DynamicsBean.ReplyTextBean replyTextBean : mDynamicsBeanList.get(dynamicPosition).getReplyText()) {
                            if (replyTextBean.getCid().equals(msgEvent.getData())) {
                                deleteReplyPosition = mDynamicsBeanList.get(dynamicPosition).getReplyText().indexOf(replyTextBean);
                            }
                        }
                        if (deleteReplyPosition != -1) {
                            mDynamicsBeanList.get(dynamicPosition).getReplyText().remove(deleteReplyPosition);
                        }
                    }
                    mAdapter.notifyItemChanged(dynamicPosition);
                }
            }
        });
    }

    public <T> void registerRxBus(Class<T> eventType, Consumer<T> action) {
        Disposable disposable = rxBus.doSubscribe(eventType, action, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {

            }
        });
        rxBus.addSubscription(this, disposable);
    }

    public void refreshDynamics() {
        if (mSrlMyRefreshLayout != null) {
            mRvDynamics.scrollToPosition(0);
            mSrlMyRefreshLayout.autoRefresh();
        }
    }
}
